<template>
  <div>
    <div class="todoapp">
      <TodoHeader
        :arr="showArr"
        @addEvent="addFn"
        @complateEvent="complateFn"
      ></TodoHeader>
      <TodoMain 
      :arr="showArr" 
      @delEvent="delFn"
      ></TodoMain>
      <TodoFooter
        :arr="showArr"
        @changeEvent="changeFn"
        @clearEvent="clearFn"
      ></TodoFooter>
    </div>
  </div>
</template>
 
<script>
// 引入App.vue-主入口页面上使用
import "./styles/base.css";
import "./styles/index.css";
// 引入组测使用
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";
export default {
  data() {
    return {
      list: JSON.parse(localStorage.getItem("todoList")) || [],
      isStr: "all", // 标记现在筛选状态
    }
  },
  computed: {
    showArr() {
      // 标记和list原数组, 筛选
      if (this.isStr === "yes") {
        // 已完成数组
        // filter过滤
        return this.list.filter((obj) => obj.isDone === true)
      } else if (this.isStr === "no") {
        return this.list.filter((obj) => obj.isDone === false)
      } else {
        return this.list
      }
    },
  },
  methods: {
    addFn(todoName) {
      let theId =
        this.list.length === 0 ? 100 : this.list[this.list.length - 1].id + 1
      this.list.push({
        id: theId,
        name: todoName,
        isDone: false,
      })
    },
    delFn(id) {
      let index = this.list.findIndex((obj) => obj.id === id)
      this.list.splice(index, 1);
    },
    // 改变筛选数据标记
    changeFn(str) {
      this.isStr = str
    },
    // 清空已完成任务的方法
    clearFn() {
      // 思路: 把未完成筛选出来, 覆盖给list数组
      this.list = this.list.filter((obj) => obj.isDone === false)
    },
    complateFn(bool) {
      this.list.forEach((obj) => {
        obj.isDone = bool;
      })
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("todoList", JSON.stringify(this.list))
      },
    },
  },
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
}
</script>